<template>
    <div>
        <div class="line">
            <label class="title">Title:</label><input class="content" v-model="title" readOnly="true"/>
        </div>
        <div class="line">
            <label class="title">Content:</label><textarea class="content" v-model="content"></textarea>
        </div>
        <div class="line">
            <button @click="save">Save</button>
            <button @click="prev">Prev</button>
        </div>
    </div>
</template>
<script>
import axios from "axios";
export default {
    data(){
        return {
            id: "",
            title:"",
            content:"",
            locked: false
        }
    },
    mounted(){
        axios.post('/api/file/find',{
                id: this.$route.query.id
            }).then(res=>{
                if(res.status == "200"){
                    if(res.data.length>0){
                        this.id = res.data[0].id;
                        this.title = res.data[0].title;
                        this.content = res.data[0].content;
                        if(res.data[0].locked === 1){
                            alert("File is locked,Please wait for a moment");
                            this.prev();
                        }else{
                            this.lock();
                        }
                    }
                }
            })

    },
    destroyed(){
        if(this.locked){
             this.unlock()
        }
    },
    methods:{
        lock(){
            axios.post('/api/file/lock',{id: this.id}).then(res=>{
                if(res.status===200){
                    this.locked = true
                    setTimeout(() => {
                        this.unlock()
                    }, 60000);
                }
            })
        },
        unlock(){
            axios.post('/api/file/unlock',{id: this.id});
        },
        save(){
            axios.post('/api/file/edit',{
                id: this.id,
                title: this.title,
                content: this.content
            }).then(res=>{
                if(res.status === 200){
                    this.$router.push("/list")
                }
            })
        },
        prev(){
            this.$router.go(-1)
        }
    }
}
</script>
<style scoped>
.line{margin-bottom:10px;}
.title{width: 10vw;vertical-align: top;}
.content{width: 30vw;}
textarea{height: 20vh}
</style>